package git.soulbgm.aop;

import git.soulbgm.common.DataBaseContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 数据源切换的AOP
 *
 * @author 贺瑞杰
 * @date 2020/08/28
 */
@Aspect
@Component
public class DataSourceAop {

    @Pointcut("!@annotation(git.soulbgm.common.annotation.Master) " +
            "&& (execution(* git.soulbgm.service..*.select*(..)) " +
            "|| execution(* git.soulbgm.service..*.get*(..))" +
            "|| execution(* git.soulbgm.service..*.find*(..))" +
            ")")
    public void readPointcut() {

    }

    @Pointcut("@annotation(git.soulbgm.common.annotation.Master) " +
            "|| execution(* git.soulbgm.service..*.insert*(..)) " +
            "|| execution(* git.soulbgm.service..*.add*(..)) " +
            "|| execution(* git.soulbgm.service..*.update*(..)) " +
            "|| execution(* git.soulbgm.service..*.edit*(..)) " +
            "|| execution(* git.soulbgm.service..*.delete*(..)) " +
            "|| execution(* git.soulbgm.service..*.remove*(..))")
    public void writePointcut() {

    }

    @Before("readPointcut()")
    public void read() {
        DataBaseContextHolder.slave();
    }

    @Before("writePointcut()")
    public void write() {
        DataBaseContextHolder.master();
    }

    @After("readPointcut()")
    public void after(JoinPoint point) {
        //清理掉当前设置的数据源，让默认的数据源不受影响
        DataBaseContextHolder.clear();
    }
}
